<template>
	<view class="centerbox">
		<view class="rechTop">
			<view class="imgTitele flex">
				<image src="/static/images/toptitleImage.png"></image>
			</view>
			<view class="ChooseTitle">
				<view class="Vertical"></view>
				<span>店铺选择</span>
			</view>
			<view class="Storefront" @click="handleClick('Store')">
			    <view class="Store_left">
			      <img src="/static/images/Store_left.png" />
			    </view>
			    <view class="Store_right">
			      <img src="/static/images/Store_top.png" />
			      <span>{{selectedStoreName || '请选择门店'}}</span>
			    </view>
			    <view class="Storeimg">
			      <img src="/static/images/rightimg.png" />
			    </view>
			  </view>
			<view class="Choosepopup choTop" @click="handleClick('chotop')">
				<view class="Amount_title">机器选择</view>
				<view class="right-img" v-if="selectedDeviceName">
					<span class="rightTitle" v-if="selectedValue">
						<img class="RadioImg" v-if="eventChild=='洗脱烘'" src="/static/images/xiyiji.png"/>
						<img class="RadioImg" v-if="eventChild=='烘干专用'" src="/static/images/hgimg.png"/>
						<img class="RadioImg" v-if="eventChild=='智能柜'" src="/static/images/zngimg.png"/>
						{{selectedDeviceName}}
					</span>
					<img src="/static/images/rightimg.png"/>
				</view>
			</view>
			<view class="AmountBox">
				<view class="flexbox">
					<view class="Amount_title">储值金额</view>
					<view class="uni-form-item uni-column inputBox">
						<view class="title">$</view>
						<wd-input v-model="Amount" placeholder="请输入金额"clearable @change="handleChange"
							@focus="showKeyBoard"></wd-input>
					</view>
				</view>
			</view>
			<view class="Choosepopups coupon">
			  <view class="couponBox" @click="handleClick('coupon')">
			    <view class="Amount_title">优惠券</view>
			    <view class="right-img">
			      <span class="spBox" v-if="seletcoupon">
			        <img src="/static/images/hongbao.png"/>
			        {{seletcoupon}}
			      </span>
			      <img src="/static/images/rightimg.png" />
			    </view>
			  </view>
			  <view class="couponBox has-border-top" v-if="discounted_amount">
			    <view class="Amount_title">实付金额</view>
			    <div class="right-img">
			      <span style="color: red; text-decoration: line-through;">{{Amount}}.00</span>
			      <span style="margin-left: 10px;">{{discounted_amount}}元</span>
			    </div>
			  </view>
			</view>
			<view class="btn">
				<button class="login-btn" @click="handlePayment()">确认</button>
			</view>
		</view>
		<wd-popup v-model="showPopup" position="bottom" @after-enter="handlePopupShow" closable
			custom-style="height: 500px;padding: 0 24rpx;">
			<view class="titlepopup">{{titlepopup}}</view>
			<wd-radio-group v-model="selectedStore" shape="dot" @change="handleRadioChange" v-if="typeshpow=='Store'">
				<view class="radio-item" v-for="item in Shoplist" :key="item.shop_id">
					<wd-radio :value="item.shop_id" >
						{{item.shop_name}}
					</wd-radio>
				</view>
			</wd-radio-group>
			<wd-tabs v-model="eventChild" ref="tabsRef" inactive-color="#999" custom-class='cuswd_tabs'
				@change="handleChange" v-if="typeshpow!='Store'">
				<wd-tab v-for="item in tabs" :key="item" :title="`${item}`" :name="item">
					<view class="radio-group-container" v-if="typeshpow=='chotop'">
						<wd-radio-group v-model="selectedValue" shape="dot" @change="handleRadioChange">
							<view class="radio-item" v-for="item in availableMachines" :key="item.device_id"
								:class="{ 'disabled-item': !isAvailable(item) }">
								<wd-radio :value="item.device_id" :disabled="!isAvailable(item)">
									<view class="radio_check">
										<img class="RadioImg" v-if="eventChild=='洗脱烘'" src="/static/images/xiyiji.png"/>
										<img class="RadioImg" v-if="eventChild=='烘干专用'" src="/static/images/hgimg.png"/>
										<img class="RadioImg" v-if="eventChild=='智能柜'" src="/static/images/zngimg.png"/>
										{{item.device_name}}
									</view>
									<text v-if="!isAvailable(item)" class="unavailable-text">(不可用)</text>
								</wd-radio>
							</view>
						</wd-radio-group>
					</view>
					<view class="radio-group-container" v-else>
						<view class="radioBox" v-for="(coupon, index) in availableCoupons" :key="index"
							:class="{ 'selected': selectedCoupon === index }" @click="selectCoupon(coupon, index)">
							<view class="radioLeft">
								<view v-if="coupon.discount_type==1">
									<span class="fontTiyle">
										{{ coupon.discount / 10}}
									</span>
									<span class="zhefongt">折</span>
								</view>
								<view v-else>
									<span class="zhefongt">$</span>
									<span class="fontTiyle">
										{{ coupon.amount }}
									</span>
								</view>
								<span>使用说明：{{ coupon.name }}</span><br>
								<span>有效期：{{ coupon.validity }}</span>
							</view>
							<view class="radioRight">
								<view class="checkbox"></view>
							</view>
						</view>
						<view class="no-coupon" :class="{ 'selected': selectedCoupon === null }" v-if="availableCoupons.length>0"
							@click="selectNoCoupon">
							<view class="radioLeft">
								<span class="fontTiyle">不选择</span>
							</view>
							<view class="radioRight">
								<view class="checkbox"></view>
							</view>
						</view>
					</view>
				</wd-tab>
			</wd-tabs>
		</wd-popup>
		<!-- <wd-number-keyboard v-model:visible="visible" mode="custom" extra-key="." close-text="完成" @input="onInput"
			@delete="onDelete"></wd-number-keyboard> -->
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, reactive } from 'vue'
	import { httpGet, httpPost } from '@/utils/http'
	import formatToChineseDateTime from '@/utils/format/formatChineseDate'
	import { useUserStore } from '@/store'
	const userStore = useUserStore()
	const Amount = ref('')
	const radioType = ref('')
	const token = uni.getStorageSync('token');
	const handleAmount = () => {
		if (!Amount.value) {
			uni.showToast({
				title: '请输入金额',
				icon: 'none',
			})
			return
		}
		if (!radioType.value) {
			uni.showToast({
				title: '请选择支付方式',
				icon: 'none',
			})
			return
		}
	}
	// const isH5 = computed(() => process.env.VUE_APP_PLATFORM === 'h5')
	// const showKeyBoard = (e) => {
	//   if (!isH5.value) {
	//     e.preventDefault() 
	//   }
	//   // visible.value = true
	// }
	const tabs = ref(['洗脱烘', '烘干专用', '智能柜'])
	const showPopup = ref(false) // 控制popup显示
	const tabsRef = ref() // 获取分段器实例
	const typeshpow = ref('')
	const titlepopup = ref('')
	const handleClick = (item) => {
		typeshpow.value = item;
		if (item == 'chotop') {
			if(!selectedStore.value){
				uni.showToast({
				  title: '请先选择门店',
				  icon: 'none',
				});
				return
			}
			titlepopup.value = '机器选择';
			tabs.value = ['洗脱烘', '烘干专用', '智能柜'];
			eventChild.value = 0;
			showPopup.value = true;
		} else if(item == 'Store'){
			titlepopup.value = '门店选择';
			showPopup.value = true;
			Getlistorders()
		}else {
			titlepopup.value = '优惠券选择';
			tabs.value = ['节庆', '包月卡', '优惠券'];
		  // 创建验证数组
		    const validations = [
			  { condition: !Amount.value, message: '请先输入金额' },
		      { condition: !selectedValue.value, message: '请先选择设备' },
		    ];
		    for (const validation of validations) {
		      if (validation.condition) {
		        uni.showToast({
		          title: validation.message,
		          icon: 'none',
		        });
		        return; 
		      }
		    }
			eventChild.value = 0;
			showPopup.value = true;
		}
	};
	// 跟新分段器样式
	const handlePopupShow = () => {
		tabsRef.value?.updateLineStyle(false)
	}
	onMounted(async () => {
		// await Getlistdevices()
	})
	const Shoplist = ref([])
	const Getlistorders = async () => {
		try {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			const response = await httpGet(
				'/miniapp/list_shops/',
				{},
				{
					'Authorization': `Bearer ${userStore.userInfo.token}`,
					'Content-Type': 'application/json;charset=utf-8'
				}
			);
			if (response.status_code == 200) {
				Shoplist.value = response.data;
			}
		} catch (error) {
			console.error('请求失败:', error);
			uni.showToast({ title: '获取失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};
	// 计算可用
	const isAvailable = (item) => {
		const availableTime = new Date(item.available_time).getTime();
		const currentTime = new Date().getTime();
		return availableTime <= currentTime;
	};
	// 计算可用的设备列表
	const availableMachines = computed(() => {
		return Machine.value.filter(item => isAvailable(item))
	})
	// 选中值
	const eventChild = ref(0)
	const handleChange = async (index, name) => {
		eventChild.value = index.index
		if (typeshpow.value == 'chotop') {
			await Getlistdevices(index)
		} else {
			await Getlistcoupons()
		}
	}
	const Machine = ref([])
	const Getlistdevices = async (item) => {
		try {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			const device = ref([])
			if (eventChild.value == 0) {
				device.value = [1, 2]
			} else if (eventChild.value == 1) {
				device.value = [3]
			} else {
				device.value = [5]
			}
			const response = await httpPost(
				'/miniapp/list_devices/',
				{
					"shop_id": selectedStore.value,
					"device_type": device.value
				},
				{},
				{
					'Authorization': `Bearer ${userStore.userInfo.token}`,
					'Content-Type': 'application/json;charset=utf-8'
				}
			);
			if (response.status_code == 200) {
				Machine.value = response.data;
			}
		} catch (error) {
			console.error('请求失败:', error);
			uni.showToast({ title: '获取失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};
	const availableCoupons = computed(() => {
		return coupons.value.filter(coupon => coupon.available === true)
	})
	const coupons = ref([])
	const Getlistcoupons = async () => {
		try {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			const response = await httpPost(
				'/miniapp/computer_coupons/',
				{
					"device_id": selectedValue.value,
					"amount": Amount.value,
					"coupon_type": eventChild.value
				},
				{},
				{
					'Authorization': `Bearer ${userStore.userInfo.token}`,
					'Content-Type': 'application/json;charset=utf-8'
				}
			);
			if (response.status_code == 200) {
				coupons.value = response.data;
			}
		} catch (error) {
			console.error('请求失败:', error);
			uni.showToast({ title: '获取失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};
	const selectedValue = ref('')
	const handleRadioChange = (value) => {
	}

	// 门店id
	const selectedStore=ref('')
	const selectedDeviceId = ref('')
	watch(
	  [() => selectedValue.value, () => selectedStore.value],
	  ([newVal1, newVal2]) => {
	    if (newVal1 || newVal2) {
	      showPopup.value = false
	    }
	  },
	  { immediate: false, deep: false }
	)
	// 机器名称
	const selectedDeviceName = computed(() => {
		const selected = Machine.value.find(item => item.device_id === selectedValue.value)
		return selected ? selected.device_name : ''
	})
	// 门店名称
	const selectedStoreName = computed(() => {
		const selected = Shoplist.value.find(item => item.shop_id === selectedStore.value)
		return selected ? selected.shop_name : ''
	})
	const handlePayment =async () => {
		await Getpayment()
	}
	const Getpayment = async () => {
		if (!selectedValue.value) {
		  uni.showToast({
		    title: '请选择机器',
		    icon: 'none'
		  });
		  return;
		}
		if (!Amount.value || parseFloat(Amount.value) <= 0) {
		    uni.showToast({
		        title: '请输入大于0的金额',
		        icon: 'none',
		    })
		    return
		}
		try {
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
			const response = await httpPost(
				'/miniapp/payment_device/',
				{
				  "amount": Amount.value,
				  "device_id": selectedValue.value,
				  "coupon_code": coupon_code.value,
				 
				},
				{},
				{
					'Authorization': `Bearer ${userStore.userInfo.token}`,
					'Content-Type': 'application/json;charset=utf-8'
				}
			);
			if (response.status_code == 200) {
				uni.showToast({ title: response.message, icon: 'none' });
				uni.navigateTo({
					url: '/pages/index/index',
				})
			}
		} catch (error) {
			console.error('请求失败:', error);
			uni.showToast({ title: '获取失败', icon: 'none' });
		} finally {
			uni.hideLoading();
		}
	};
	const selectedCoupon = ref<number | null>(null)
	// 选择优惠券
	const seletcoupon = ref('')
	const discounted_amount=ref('')
	const coupon_code=ref('')
	const selectCoupon = (coupon : object, index : number) => {
		// console.log(coupon);
		showPopup.value = false
		console.log(coupon);
		coupon_code.value=coupon.coupon_code
		discounted_amount.value=coupon.discounted_amount
		seletcoupon.value = coupon.name
		selectedCoupon.value = index
	}

	const selectNoCoupon = () => {
		seletcoupon.value = ''
		showPopup.value = false
		selectedCoupon.value = null
	}
	// const visible = ref<boolean>(false)
	// const onInput = (value : string) => {
	// 	Amount.value += value;
	// }
	// const onDelete = () => {
	// 	if (Amount.value.length > 0) {
	// 		Amount.value = Amount.value.slice(0, -1);
	// 	}
	// }
</script>
<style scoped>
	.radio-group-container {
		padding: 20rpx;

	}

	/deep/.wd-radio-group {
		background-color: transparent;
	}

	:deep(.wd-input) {
		width: 100%;
	}

	:deep(.uni-input-placeholder) {
		font-size: 38rpx;
	}

	:deep(.uni-input-input) {
		font-size: 50rpx;
	}

	.radio-item {
		margin-bottom: 20rpx;
		padding: 15rpx 0;
	}
	.radio_check{
		display: flex;
		align-items: center;
	}
	.RadioImg{
		width: 80rpx;
		height: 80rpx;
	}
	:deep(.wd-key--close) {
		background-color: black !important;
	}
</style>
<style lang="scss" scoped>
	.btn {
		padding-bottom: 20rpx;
	}
	.login-btn {
		width: calc(100% - 80rpx);
		height: 80rpx;
		margin-top: 32rpx;
		margin-left: 40rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
		opacity: 1;
		border-radius: 40rpx;
		color: #fff;
		font-size: 30rpx;
		background: rgba(0, 0, 0, 1);
	
	}
	.Choosepopups {
		width: calc(100% - 80rpx);
		margin-left: 40rpx;
		padding: 30rpx;
		border-radius: 20rpx;
		background-color: white;
		box-sizing: border-box;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
		.couponBox{
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;
			.right-img {
				display: flex;
				align-items: center;
				gap: 10rpx;
			
				img {
					width: 28rpx;
					height: 16rpx;
				}
			
				.rightTitle {
					display: flex;
					align-items: center;
					margin-right: 10rpx;
			
					img {
						width: 60rpx;
						height: 60rpx;
					}
				}
			
				.spBox {
					display: block;
					border-radius: 8rpx;
					padding: 8rpx 10px;
					font-size: 24rpx;
					color: black;
					background: rgba(255, 236, 230, 1);
					display: flex;
					align-items: center;
					gap: 10rpx;
			
					img {
						width: 24rpx;
						height: 30rpx;
					}
				}
			}
		}
		.has-border-top {
		  border-top: 1px solid rgba(230, 230, 230, 1);
		}
		}
	.radioBox {
		height: 180rpx;
		opacity: 1;
		padding: 40rpx;
		border-radius: 20rpx;
		margin-bottom: 40rpx;
		display: flex;
		align-items: center;
		background: rgba(255, 236, 230, 1);
		justify-content: space-between;

		.radioLeft {
			color: rgba(241, 71, 37, 0.6);

			.fontTiyle {
				font-size: 88rpx;
			}

			.zhefongt {
				font-size: 40rpx;
				font-weight: 700;
			}
		}

		.radioRight {
			width: 32rpx;
			/* 18px */
			height: 32rpx;
			background: #fff;
			border: 1px solid rgba(230, 230, 230, 1);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;

			.checkbox {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				background-color: transparent;
				transition: all 0.3s ease;
			}
		}

		&.selected {
			.radioLeft {
				color: rgba(241, 71, 37, 1);
			}

			.radioRight {
				background: rgba(241, 71, 37, 1);
				border-color: rgba(241, 71, 37, 1);
			}
		}


	}

	.no-coupon {
		height: 120rpx;
		border-radius: 20rpx;
		padding: 0 40rpx;
		background: rgba(243, 247, 255, 1);
		display: flex;
		align-items: center;
		justify-content: space-between;

		.radioLeft {
			.fontTiyle {
				font-size: 30rpx;
				font-weight: normal;
				color: #000;
			}
		}

		.radioRight {
			width: 32rpx;
			height: 32rpx;
			background: #fff;
			border: 1px solid rgba(230, 230, 230, 1);
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;

			.checkbox {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				background-color: transparent;
				transition: all 0.3s ease;
			}
		}

		&.selected {
			.radioLeft {
				color: rgba(241, 71, 37, 1);
			}

			.radioRight {
				background: rgba(241, 71, 37, 1);
				border-color: rgba(241, 71, 37, 1);
			}
		}
	}

	.titlepopup {
		display: flex;
		font-size: 32rpx;
		align-items: center;
		justify-content: center;
		padding: 24rpx 0;
		border-bottom: 1px solid rgba(230, 230, 230, 1);

	}

	.cuswd_tabs {}

	.flex {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.boxPublic {
		width: calc(100% - 80rpx);
		height: 320rpx;
		padding: 30rpx;
		box-sizing: border-box;
	}

	.Amount_title {
		font-size: 32rpx;
		color: rgba(0, 0, 0, 1);
	}

	.centerbox {
		width: 100%;
		height: 100%;

		.rechTop {
			width: 100%;
			height: 400rpx;
			background-color: black;
			position: relative;
			padding-top: constant(safe-area-inset-top);
			padding-top: env(safe-area-inset-top);
			.ChooseTitle {
				padding-left: 40rpx;
				color: #fff;
				display: flex;
				height: 30rpx;
				font-size: 30rpx;
				margin-top: 100rpx;
				align-items: center;

				.Vertical {
					width: 7rpx;
					height: 100%;
					margin-right: 8rpx;
					background: rgba(255, 255, 255, 1);
				}
			}

			.imgTitele>image {
				margin-top: 60rpx;
				width: 360rpx;
				height: 40rpx;
			}

			.Storefront {
				position: absolute;
				width: calc(100% - 80rpx);
				height: 180rpx;
				bottom: -50rpx;
				left: 40rpx;
				padding: 30rpx;
				box-sizing: border-box;
				background-color: white;
				border-radius: 20rpx;
				display: flex;
				box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
				.Storeimg{
					position: absolute;
					top: 50%;
					right: 30rpx;
					transform:translate(0,-50%);
					img{
						width: 28rpx;
						height: 16rpx;
					}
				}
				.Store_left {
					img {
						width: 120rpx;
						height: 120rpx;
					}
				}

				.Store_right {
					margin-left: 32rpx;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					img {
						width: 360rpx;
						height: 40rpx;
					}

					span {
						font-size: 30rpx;
						color: rgba(0, 0, 0, 1);
					}
				}
			}

			.choTop {
				margin-top: 260rpx;
			}

			.coupon {
				margin-top: 35rpx;
			}

			.Choosepopup {
				width: calc(100% - 80rpx);
				height: 120rpx;
				margin-left: 40rpx;
				padding: 30rpx;
				border-radius: 20rpx;
				background-color: white;
				box-sizing: border-box;
				box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
				display: flex;
				justify-content: space-between;
				align-items: center;
				.right-img {
					display: flex;
					align-items: center;
					gap: 10rpx;

					img {
						width: 28rpx;
						height: 16rpx;
					}

					.rightTitle {
						display: flex;
						align-items: center;
						margin-right: 10rpx;

						img {
							width: 60rpx;
							height: 60rpx;
						}
					}

					.spBox {
						display: block;
						border-radius: 8rpx;
						padding: 8rpx 10px;
						font-size: 24rpx;
						color: black;
						background: rgba(255, 236, 230, 1);
						display: flex;
						align-items: center;
						gap: 10rpx;

						img {
							width: 24rpx;
							height: 30rpx;
						}
					}
				}
			}

			.AmountBox {
				width: calc(100% - 80rpx);
				height: 320rpx;
				padding: 30rpx;
				margin-top: 35rpx;
				margin-left: 40rpx;
				box-sizing: border-box;
				background-color: white;
				border-radius: 20rpx;
				box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);

				.inputBox {
					height: 80rpx;
					display: flex;
					margin-top: 130rpx;
					align-items: flex-end;

					.placeholder {
						font-size: 50rpx;
						font-weight: 400;
						letter-spacing: 0px;
						color: rgba(153, 153, 153, 1);
					}

					.title {
						font-size: 40rpx;
						color: rgba(0, 0, 0, 1);
						margin-right: 10rpx;
						// margin-bottom: 8rpx;
					}

					.uni-input {
						width: 100%;
						height: 80rpx;
						line-height: normal;

						::v-deep(.uni-input-input) {
							font-size: 50rpx;
						}
					}
				}
			}
		}
	}
</style>